function y = FitPWF_PL(x, ...
                       AllSlope, TP)
% The code is based on the following paper:
%   Chen, T. Y., Lin, Y. L., and Tzeng, L. Y., forthcoming.
%   Estimating probability weighting functions through option pricing bounds. Review of Asset Pricing Studies.
%
% Copyright: Tzu-Ying Chen, Yo-Lan Lin, Larry Y. Tzeng
% Date: January 30, 2024
                   
AllTP = linspace(0, 1, 1 + length(AllSlope));
AllTP(1) = [];                                                             
dx = 1 / length(AllSlope);

y = nan(size(x));                                                           
if length(TP) > 0
    [~, Index_TP] = min(abs(AllTP - TP));

    for i = 1:Index_TP
        if i > 1
            Index = find((x >= AllTP(i - 1)) & ...
                         (x <= AllTP(i)));   
            y(Index) = dx * sum(AllSlope(1:(i - 1))) + ...
                       AllSlope(i) * (x(Index) - AllTP(i - 1));                 
        else
            Index = find(x <= AllTP(i));      
            y(Index) = AllSlope(i) * x(Index);  
        end
        clear Index
    end

    for i = (Index_TP + 1):length(AllSlope)
        Index = find((x >= AllTP(i - 1)) & ...
                     (x <= AllTP(i)));  
             
        if i > (Index_TP + 1)
            y(Index) = TP + ...
                       dx * sum(AllSlope((Index_TP + 1):(i - 1))) + ...
                       AllSlope(i) * (x(Index) - AllTP(i - 1));    
        else
            y(Index) = TP + ...
                       AllSlope(i) * (x(Index) - TP);
        end
        clear Index 
    end
else
    for i = 1:length(AllSlope)
        if i > 1
            Index = find((x >= AllTP(i - 1)) & ...
                         (x <= AllTP(i)));   
            y(Index) = dx * sum(AllSlope(1:(i - 1))) + ...
                       AllSlope(i) * (x(Index) - AllTP(i - 1));                 
        else
            Index = find(x <= AllTP(i));      
            y(Index) = AllSlope(i) * x(Index);  
        end
        clear Index
    end 
end